package mylibrary.io.nio.nonBlock.sample2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Client implements Runnable{

	private FileChannel fileChannel;
	private Selector selector ;
	private ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
	
	public void run() {
		
		System.out.println("11111111");
		
		try {
		if(selector == null) {
			selector = Selector.open();
		}
		
		SocketChannel client = SocketChannel.open();
		client.configureBlocking(false);
		client.connect(new InetSocketAddress("localhost", 1234));
		client.register(selector, SelectionKey.OP_CONNECT);
		
		while(true) {
			
			System.out.println("222222111");
			
			selector.select();
			Iterator it = selector.selectedKeys().iterator();
			
			while(it.hasNext()) {
				SelectionKey key = (SelectionKey) it.next();
				it.remove();
				
				if(key.isConnectable()) {
					
					System.out.println("33333333333");
					
					SocketChannel channel = (SocketChannel) key.channel();
					if(channel.isConnectionPending()) {
						channel.finishConnect();
					}
					channel.write(ByteBuffer.wrap("Give me a file".getBytes()));
					//channel.register(selector, SelectionKey.OP_WRITE);
					channel.register(selector, SelectionKey.OP_READ);
				}
				
				else if(key.isReadable()) {
					
					System.out.println("Client receives data");
					
					
					SocketChannel channel = (SocketChannel) key.channel();
//					byteBuffer.clear();
//					channel.read(byteBuffer);
//					for(int i=0; i<byteBuffer.array().length; i++)
//					System.out.println(byteBuffer.array()[i]);
					
					channel.close();
					key.cancel();
				}
			}
		}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
				
		Thread thread1 = new Thread(new Client());
		Thread thread2 = new Thread(new Client());
		
		thread1.start();
		thread2.start();
		
		
	}
	
	
}
